<?php

namespace app\common\model;

use app\common\model\coupon\Log;
use app\common\model\order\Order;
use think\Db;
use think\Model;

/**
 * 会员模型
 */
class User extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'url',
        'join_date',
        'sales_volume',
        'qr_image_str',
    ];
    public function groups()
    {
        return $this->belongsTo('app\common\model\user\UserGroup', 'group_id', 'id', [], 'LEFT');
    }
    public function levels()
    {
        return $this->belongsTo('app\common\model\user\Level', 'level', 'id', [], 'LEFT');
    }
    public function getQrImageStrAttr($value, $data)
    {
        return $data['qr_image'] ? cdnurl($data['qr_image'], true) : '';
    }

    /**
     * 获取个人URL
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getUrlAttr($value, $data)
    {
        return "/u/" . $data['id'];
    }
    public function getJoindateAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['jointime']) ? $data['jointime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }
    /**
     * 获取个人销量
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getSalesVolumeAttr($value, $data)
    {
        return Order::where('user_id', $data['id'])->where('status', '>', '0')->sum('pay_money');
    }
    /**
     * 获取头像
     * @param string $value
     * @param array  $data
     * @return string
     */
    public function getAvatarAttr($value, $data)
    {
        if (!$value) {
            //如果不需要启用首字母头像，请使用
            //$value = '/assets/img/avatar.png';
            $value = letter_avatar($data['nickname']);
        }
        return $value;
    }

    /**
     * 获取会员的组别
     */
    public function getGroupAttr($value, $data)
    {
        return UserGroup::get($data['group_id']);
    }

    /**
     * 获取验证字段数组值
     * @param string $value
     * @param array  $data
     * @return  object
     */
    public function getVerificationAttr($value, $data)
    {
        $value = array_filter((array)json_decode($value, true));
        $value = array_merge(['email' => 0, 'mobile' => 0], $value);
        return (object)$value;
    }

    /**
     * 设置验证字段
     * @param mixed $value
     * @return string
     */
    public function setVerificationAttr($value)
    {
        $value = is_object($value) || is_array($value) ? json_encode($value) : $value;
        return $value;
    }

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $money != 0) {
                $before = $user->money;
                //$after = $user->money + $money;
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;
                //更新会员信息
                $user->save(['money' => $after]);
                //写入日志
                MoneyLog::create(['user_id' => $user_id, 'money' => $money, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 变更会员积分
     * @param int    $score   积分
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function score($score, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user = self::lock(true)->find($user_id);
            if ($user && $score != 0) {
                $before = $user->score;
                $after = $user->score + $score;
                $level = self::nextlevel($after);
                //更新会员信息
                $user->save(['score' => $after, 'level' => $level]);
                //写入日志
                ScoreLog::create(['user_id' => $user_id, 'score' => $score, 'before' => $before, 'after' => $after, 'memo' => $memo]);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
        }
    }

    /**
     * 根据积分获取等级
     * @param int $score 积分
     * @return int
     */
    public static function nextlevel($score = 0)
    {
        $lv = array(1 => 0, 2 => 30, 3 => 100, 4 => 500, 5 => 1000, 6 => 2000, 7 => 3000, 8 => 5000, 9 => 8000, 10 => 10000);
        $level = 1;
        foreach ($lv as $key => $value) {
            if ($score >= $value) {
                $level = $key;
            }
        }
        return $level;
    }

    /**
     * 根据消费升级代理登录
     * @param int $score 积分
     * @return int
     */
    public static function nextGroup($money = 0, $uid)
    {
        $lv = UserGroup::column('id,task');
        $user = self::get($uid);
        foreach ($lv as $key => $value) {
            if ($money >= $value) {
                $group = $key;
            }
        }

        if ($group > $user->group_id) {
            if ($user->group_id == 1) {
                $user->grouptime = time();
            }
            // if ($user->group_id < 2 && $group >= 2) {
            //     for ($i = 0; $i < 10; $i++) {
            //         Log::getCoupon(5, $uid, false);
            //     }
            // }
            // if ($user->group_id < 3 && $group >= 3) {
            //     for ($i = 0; $i < 20; $i++) {
            //         Log::getCoupon(5, $uid, false);
            //     }
            // }
            // if ($user->group_id < 4 && $group >= 4) {
            //     for ($i = 0; $i < 30; $i++) {
            //         Log::getCoupon(5, $uid, false);
            //     }
            // }
            $user->group_id = $group;
        }
        $user->consumption = $money;
        $user->save();
    }

    /**
     * 根据星级升级
     * @param int $score 积分
     * @return int
     */
    public static function starUpgrade($pids)
    {
        $users = User::whereIn('id', $pids)->where('level', '<>', 7)->orderRaw("field(id, $pids)")->select();

        foreach ($users as $v) {
            $nextUserIds = User::where("pid", $v->id)->column('id');
            // $member = User::whereIn("id", $nextUserIds)->column('id,level');
            $member = User::where("find_in_set({$v->id},paren_ids)")->column('id,level');

            $total_money = Order::where('status', '>', 0)->whereIn('user_id', array_keys($member))->sum('pay_money');

            if ($total_money >= 100000) {
                $count = array_count_values($member);
                if ($v->level == 0 && count($nextUserIds) >= 3) {
                    $v->level = 1;
                }
                if ($v->level == 1 && isset($count[1]) && $count[1] >= 2) {
                    $v->level = 2;
                }
                if ($v->level == 2 && isset($count[2]) && $count[2] >= 2) {
                    $v->level = 3;
                }
                if ($v->level == 3 && isset($count[3]) && $count[3] >= 2) {
                    $v->level = 4;
                }
                if ($v->level == 4 && isset($count[4]) && $count[4] >= 2) {
                    $v->level = 5;
                }
                if ($v->level == 5 && isset($count[5]) && $count[5] >= 2) {
                    $v->level = 6;
                }
                if ($v->level == 6 && isset($count[6]) && $count[6] >= 2) {
                    $v->level = 7;
                }
                $v->save();
            }
        }
    }
    /**
     * 检查星级升级
     * @param int $score 积分
     * @return int
     */
    public static function checkStar($uid)
    {
        $users = User::get($uid);
        if ($users->level < 7) {
            $nextUserIds = User::where("pid", $uid)->column('id');

            $member = User::where("find_in_set({$users->id},paren_ids)")->column('id,level');
            $total_money = Order::where('status', '>', 0)->whereIn('user_id', array_keys($member))->sum('pay_money');

            if ($total_money >= 100000) {
                $count = array_count_values($member);

                if ($users->level == 0 && count($nextUserIds) >= 3) {
                    $users->level = 1;
                }
                if ($users->level == 1 && isset($count[1]) && $count[1] >= 2) {
                    $users->level = 2;
                }
                if ($users->level == 2 && isset($count[2]) && $count[2] >= 2) {
                    $users->level = 3;
                }
                if ($users->level == 3 && isset($count[3]) && $count[3] >= 2) {
                    $users->level = 4;
                }
                if ($users->level == 4 && isset($count[4]) && $count[4] >= 2) {
                    $users->level = 5;
                }
                if ($users->level == 5 && isset($count[5]) && $count[5] >= 2) {
                    $users->level = 6;
                }
                if ($users->level == 6 && isset($count[6]) && $count[6] >= 2) {
                    $users->level = 7;
                }
                $users->save();
            }
        }
    }
}
